using System;
using System.IO;
using System.Threading.Tasks;

namespace RandomSearch.VM {
    public class SearchServerDomain : IDisposable {
        private readonly AppDomain _domain;
        private bool _disposed;

        public SearchServerDomain(Uri serverAdress) {
            string adress = serverAdress.AbsoluteUri;

            var domainSetup = new AppDomainSetup
                                  {
                                      ApplicationBase = AppDomain.CurrentDomain.BaseDirectory,
                                      ConfigurationFile = "App.config",
                                      ShadowCopyFiles = "true",
                                      DynamicBase = AppDomain.CurrentDomain.DynamicDirectory,
                                      ShadowCopyDirectories = "Libraries"
                                  };
            _domain = AppDomain.CreateDomain("ServicesHost", AppDomain.CurrentDomain.Evidence, domainSetup);

            var t = new Task(() => _domain.ExecuteAssembly("RandomSearch.Host.exe", new[] {adress}));
            t.Start();
        }

        #region IDisposable Members

        public void Dispose() {
            if (_disposed) return;
            AppDomain.Unload(_domain);
            _disposed = true;
        }

        #endregion

        ~SearchServerDomain() {
            if (!_disposed) Dispose();
        }
    }
}